//
//  HomeNeedContentTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/10/29.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "SubjectRecommendContentTabVC.h"
#import "HomeNeedContentHeaderView.h"
#import "DemandCell.h"
#import "DemandContentHeadCell.h"
#import "ServiceCell.h"
#import "SpecialRecommendationModel.h"
#import "HomeModel.h"
#import "DemandTheHallContentVC.h"
#import "ServiceModel.h"
#import "ServiceContentTabVC.h"
@interface SubjectRecommendContentTabVC ()<DemandCellDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong) UITableView  *tableView;
@property(nonatomic,strong) NSMutableArray *dataMuta;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,assign) int indexS;
@property(nonatomic,strong) UIButton *collectBtn;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@end
static NSString *identifierNeedContent = @"DemandCell";
static NSString *identifierSub = @"DemandContentHeadCell";
static NSString *identifier = @"ServiceCell";
@implementation SubjectRecommendContentTabVC
-(NSMutableArray *)dataMuta
{
    if (!_dataMuta) {
        _dataMuta = [NSMutableArray array];
    }
    return _dataMuta;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        CGRect frame = CGRectMake(0, 0, kVWidth, kVHeight-kNavAndStatusHight-kStatusBarHeight*2);
        _tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = kWhite;
    [self.view addSubview:self.tableView];
    self.edgesForExtendedLayout= UIRectEdgeNone;
    self.manager = [AFHTTPSessionManager manager];
    HomeNeedContentHeaderView *homeHeaderView = [[HomeNeedContentHeaderView alloc]initWithFrame:CGRectMake(0, 0, kVWidth, kVWidth/750*350)];
    homeHeaderView.specialModel = self.specialModel;
    self.tableView.tableHeaderView = homeHeaderView;
     [self.tableView registerNib:[UINib nibWithNibName:@"DemandCell" bundle:nil] forCellReuseIdentifier:identifierNeedContent];
    [self.tableView registerNib:[UINib nibWithNibName:@"DemandContentHeadCell" bundle:nil] forCellReuseIdentifier:identifierSub];
     [self.tableView registerNib:[UINib nibWithNibName:@"ServiceCell" bundle:nil] forCellReuseIdentifier:identifier];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectDemandByIds:) name:@"selectDemandByIds" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listByIds:) name:@"listByIds" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertCollection:) name:@"insertCollection" object:nil];
    
    
}
- (void)setIndex:(NSInteger)index
{
    _index = index;
    if (index == 0) {
        self.navigationItem.title = @"需求专题详情";
    }else {
        self.navigationItem.title = @"服务专题详情";
    }
    [self reloadInternetData];
}
- (void)setSpecialModel:(SpecialRecommendationModel *)specialModel
{
    _specialModel = specialModel;
    self.collectBtn = [[UIButton alloc]initWithFrame:CGRectMake(kUIScreen.size.width-20-16, kNavAndStatusHight +kStatusBarHeight+12, 22, 20)];
    [self.view addSubview:self.collectBtn];
    //    [self.sureBtn setBackgroundColor:kOrangeBg];
    [self.collectBtn addTarget: self action:@selector(clickCollect:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectBtn setImage:[UIImage imageNamed:@"shoucang2"] forState:UIControlStateNormal];
    [self.collectBtn setImage:[UIImage imageNamed:@"shoucang"] forState:UIControlStateSelected];
    if ([specialModel.collectionStatus integerValue] == 0) {
        self.collectBtn.selected = NO;
    }else {
        self.collectBtn.selected = YES;
    }
}
#pragma mark-收藏
-(void)clickCollect:(UIButton *)collectBtn
{
    NSString *ids = [NSString stringWithFormat:@"%ld",self.specialModel.id];
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                collectBtn.selected = !collectBtn.selected;
                NSString *statuS = [NSString stringWithFormat:@"%d",collectBtn.selected];
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"id":ids,
                              @"type":@"4",
                              @"status":statuS,
                              @"token":[UserDefaultsHelper readToken]
                              };
                XLog(@"self.dict:%@",self.dict);
                self.urlString = [NSString stringWithFormat:@"%@/collection/insertCollection",kUrl];
                [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    XLog(@"responseObject:%@",responseObject);
                    NSString *message = [responseObject objectForKey:@"message"];
                    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
                    __weak typeof (self)weakSelf = self;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        if (weakSelf.returnValueBlock) {
                            weakSelf.returnValueBlock(collectBtn.selected);
                        };
                    });
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
    
    
}
-(void)listByIds:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSArray *date = [dict objectForKey:@"date"];
    for (NSDictionary *dict in date) {
        ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
        [self.dataMuta addObject:model];
    }
    XLog(@"self.dataMuta.count:%ld",self.dataMuta.count);
    [self.tableView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [WSProgressHUD dismiss];
    });
}

-(void)selectDemandByIds:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSArray *temp = [dict objectForKey:@"date"];
    
    if (temp.count) {
        for (NSDictionary *dict in temp) {
            if (self.index == 0) {
                HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                [self.dataMuta addObject:model];
                
            }else {
                ServiceModel *model =[ServiceModel mj_objectWithKeyValues:dict];
                [self.dataMuta addObject:model];
            }
        }
        [self.tableView reloadData];
        [WSProgressHUD dismiss];
    }
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)reloadInternetData
{
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    self.dataMuta = nil;
    self.dict = @{
                  @"ids":self.specialModel.ids
                  };
    XLog(@"self.specialModel.ids:%@",self.specialModel.ids);
    if (self.index == 0) {
        self.indexS = 21;
    }else {
        self.indexS = 22;
    }
    [CustomeManager POSTWithURLIndex:self.indexS parameters:self.dict success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
    
}
//#pragma mark-代理:网络请求失败
//-(void)qingqiusibai:(NSNotification *)info
//{
//
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else {
        return self.dataMuta.count?self.dataMuta.count:0;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        DemandContentHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierSub forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
         XLog(@"self.specialMuta:%@",self.specialMuta);
         SpecialRecommendationModel *model = self.specialModel;
        cell.specialModel = model;
        return cell;
    }else {
        if (self.index == 0) {
            DemandCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierNeedContent forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            cell.indexPath = indexPath;
            HomeModel *model = self.dataMuta[indexPath.row];
            cell.homeModel = model;
            return cell;
        }else {
            ServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            ServiceModel *model = self.dataMuta[indexPath.row];
            cell.serviceModel = model;
            return cell;
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0;
    if (indexPath.section == 0) {
         SpecialRecommendationModel *model = self.specialModel;
        CGFloat height = [MCLabel getHeightWithTitle:model.represent withFontSize:14];
        height = 95+14+height;
        return height;
    }else {
        height = 144;
        return height;
        
    }
}

- (void)DemandCell:(nonnull DemandCell *)DemandCell withClickBtn:(nonnull UIButton *)clickBtn withIndexPath:(nonnull NSIndexPath *)indexPath withHomeModel:(nonnull HomeModel *)homeModel {
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section != 0) {
        if (self.index == 0) {
        
            DemandTheHallContentVC *homeServiceVC = [[DemandTheHallContentVC alloc]init];
            homeServiceVC.urlString = @"/demand/selectTwoDemand";
            
            XLog(@"indexPath.row:%ld",indexPath.row);
            homeServiceVC.homeModel = self.dataMuta[indexPath.row];
            [self.navigationController pushViewController:homeServiceVC animated:YES];
        }else {
            ServiceContentTabVC *homeServiceVC = [[ServiceContentTabVC alloc]init];
            homeServiceVC.model = self.dataMuta[indexPath.row];
            [self.navigationController pushViewController:homeServiceVC animated:YES];
        }
    }
}
#pragma mark-代理:显示联系人
-(void)demandCell:(DemandCell *)demandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                HomeModel *model = self.dataMuta[indexPath.row];
                model.show = clickBtn.selected;
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
}
#pragma mark-代理:收藏
- (void)demandCell:(DemandCell *)demandCell withCollectBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else{
        
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            //            NSString *message = [responseObject objectForKey:@"message"];
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                clickBtn.selected = !clickBtn.selected;
                NSString *ids = [NSString stringWithFormat:@"%ld",homeModel.id];
                NSString *status = [NSString stringWithFormat:@"%d",clickBtn.selected];
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"id":ids,
                              @"type":@"1",
                              @"status":status,
                              @"token":[UserDefaultsHelper readToken]
                              };
                XLog(@"self.dict:%@",self.dict);
                [CustomeManager POSTWithURLIndex:34 parameters:self.dict success:^(NSDictionary *dict) {
                } failure:^(NSError *error) {
                    //                    NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
                    ////                    if (status == 200) {
                    ////                    }
                }];
                
            }else {
                [LogOutAccount presentOutAccount];
                [UIAlertViewWarningAccount showWarningAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
#pragma mark-代理:收藏成功
-(void)insertCollection:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSString *message = [dict objectForKey:@"message"];
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    
}
@end
